﻿
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace User_manage
{
    [Serializable]
    public partial class User_manageForm : MaterialForm
    {
        public delegate void User_FormClosed(object sender, FormClosedEventArgs e);
        public event User_FormClosed _FormClosed;

        private int a_sn = -1;           //行数
        private Boolean add_state = false;      //添加状态
        private Boolean update_state = false;    //修改状态
       
        public User_manageForm()
        {
            InitializeComponent();

            //优化dataGridView控件闪耀现象
            Type dgvType = dataGridView1.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(dataGridView1, true, null);

            //禁止用户改变列宽行高
            dataGridView1.AllowUserToOrderColumns = false;
            dataGridView1.AllowUserToResizeRows = false;
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;

            dataGridView1.AllowUserToDeleteRows = false;
            dataGridView1.AllowUserToResizeColumns = false;
            dataGridView1.AllowUserToResizeRows = false;
            //禁止编辑
            dataGridView1.ReadOnly = true;

            //禁止用户排序
            if (dataGridView1.Columns.Count > 0)
            {
                for (int i = 0; i < dataGridView1.Columns.Count; i++)
                {
                    dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
                }
            }

            //
            groupBox1.MouseUp += new MouseEventHandler(groupBox1_Mouse);
        }

        private void User_manageForm_Load(object sender, EventArgs e)
        {
            init_DataTable();
            add_butt.Enabled = true;
            modify_butt.Enabled = true;
            delete_butt.Enabled = false;
            save_butt.Enabled = false;

            text_passwordA.Visible = false;
            text_passwordB.Visible = false;
            text_password.Visible = false;
            text_User.ReadOnly = true;
            text_admin.Enabled = false;
        }

        private void User_manageForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_DataTable != null)
            {
                Serialize(_DataTable, Application.StartupPath + "\\Config\\UserInfo.config");

            }

            _FormClosed?.Invoke(sender,e);

            //this.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            //this.Close();
        }
        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                DataGridViewRow r = this.dataGridView1.Rows[i];
                //r.HeaderCell.Value = string.Format("{0}", i + 1);
                r.Cells[0].Value = string.Format("{0}", i + 1);
            }
            this.dataGridView1.Refresh();
        }

        private void add_butt_Click(object sender, EventArgs e)
        {
            add_state = true;
            update_state = false;
            modify_butt.Enabled = false;
            delete_butt.Enabled = false;
            save_butt.Enabled = true;

            text_passwordA.Visible = false;
            text_passwordB.Visible = true;
            text_password.Visible = true;
            text_User.ReadOnly = false;
            text_admin.Enabled = true;
        }

        private void modify_butt_Click(object sender, EventArgs e)
        {
            if (a_sn <= -1)
            {
                MessageBox.Show("未选择指定用户名！", "提示！");
                return;
            }
            add_state = false;
            update_state = true;
            add_butt.Enabled = false;
            delete_butt.Enabled = false;
            save_butt.Enabled = true;

            text_passwordA.Visible = true;
            text_passwordB.Visible = true;
            text_password.Visible = true;
            text_User.ReadOnly = true;
            text_admin.Enabled = true;
        }

        private void delete_butt_Click(object sender, EventArgs e)
        {
            add_butt.Enabled = false;
            modify_butt.Enabled = false;
            save_butt.Enabled = false;

            text_passwordA.Visible = false;
            text_passwordB.Visible = false;
            text_password.Visible = false;
            text_User.ReadOnly = true;
            text_admin.Enabled = false;
            delete_user();
        }

        private void save_butt_Click(object sender, EventArgs e)
        {
            if (add_state)
            {
                if (add_user())
                {
                    add_butt.Enabled = true;
                    modify_butt.Enabled = true;
                    delete_butt.Enabled = false;
                    save_butt.Enabled = false;

                    text_passwordA.Visible = false; text_User.Text = "";
                    text_passwordB.Visible = false; text_passwordA.Text = "";
                    text_password.Visible = false; text_passwordB.Text = "";
                    text_User.ReadOnly = true; text_password.Text = "";
                    text_admin.Enabled = false;
                    add_state = false;
                    update_state = false;
                }
            }
            if (update_state)
            {
                if (update_user())
                {
                    add_butt.Enabled = true;
                    modify_butt.Enabled = true;
                    delete_butt.Enabled = false;
                    save_butt.Enabled = false;
                    text_passwordA.Visible = false; text_passwordA.Text = "";
                    text_passwordB.Visible = false; text_passwordB.Text = "";
                    text_password.Visible = false; text_password.Text = "";
                    text_User.ReadOnly = true; text_User.Text = "";
                    text_User.Enabled = false;
                    add_state = false;
                    update_state = false;
                }
            }

        }

        private void cancel_butt_Click(object sender, EventArgs e)
        {
            a_sn = -1;
            add_butt.Enabled = true;
            modify_butt.Enabled = true;
            delete_butt.Enabled = false;
            save_butt.Enabled = false;

            text_passwordA.Visible = false;
            text_passwordB.Visible = false;
            text_password.Visible = false;
            text_User.ReadOnly = true;
            text_admin.Enabled = false;
            add_state = false;
            update_state = false;

            text_passwordA.Text = String.Empty;
            text_passwordB.Text = String.Empty;
            text_password.Text = String.Empty;
            text_User.Text = String.Empty;
        }

        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            delete_butt.Enabled = true;
            string[] str = gridview_tobox(e.RowIndex, e.ColumnIndex);
            if (str!=null && str.Length>0)
            {
                text_User.Text = str[1];
                text_admin.Text = str[2];
            }
        }

        private void groupBox1_Mouse(object sender, MouseEventArgs e)
        {
            delete_butt.Enabled = false;
        }

        /**************************************************************************************************/
        //
        public DataTable _DataTable = null;

        private void init_DataTable()
        {
            DataTable buf = Deserialize<DataTable>(Application.StartupPath + "\\Config\\UserInfo.config");
            if (buf == null)
            {
                string[] user_buf = new string[] { "用户", "权限", "密码" };
                _DataTable = new DataTable();
                for (int count = 0; count < 3; count++)
                {
                    DataColumn dc = new DataColumn(user_buf[count].ToString());
                    _DataTable.Columns.Add(dc);
                }
                ;
            }
            else
            {
                _DataTable = buf;
                GridviewShowDataTable(_DataTable, dataGridView1);
            }
        }

        //判断不能重复用户名
        private Boolean not_User(ref string id)
        {
            try
            {
                DataTable dt = GetDataGridView(dataGridView1);
                for (int i = 0; i < dt.Rows.Count; i++)
                    if (text_User.Text == dt.Rows[i].ItemArray[1].ToString())
                    { id = text_User.Text; return false; }
            }
            catch { return false; }
            return true;
        }

        //添加用户
        public Boolean add_user()
        {
            try
            {
                //判断不能为空
                if ((text_User.Text == string.Empty) || (text_admin.Text == string.Empty) || (text_passwordB.Text == string.Empty) || (text_password.Text == string.Empty))
                {
                    MessageBox.Show("有项目为空，请重新输入!", "系统提示");
                    return false;
                }

                //判断是否重复
                string str = "";
                if (!not_User(ref str))
                {
                    MessageBox.Show("产品参数新增失败,有重复名称。 '" + str + "'已存在！", "Err提示！");
                    return false;
                }

                //判断密码二次输入是否正确
                if (text_passwordB.Text.Trim() != text_password.Text.Trim())
                {
                    MessageBox.Show("新密码两次输入不匹配。请重新输入！", "Err提示！");
                    return false;
                }


                //开始写入
                string bufdtr= Sha1Sign(text_password.Text, Encoding.UTF8);

                DataRow dr = _DataTable.NewRow();
                dr["用户"] = text_User.Text;
                dr["权限"] = text_admin.Text;
                dr["密码"] = bufdtr;
                _DataTable.Rows.Add(dr);
                GridviewShowDataTable(_DataTable, dataGridView1);
                MessageBox.Show("用户名添加成功！", "提示！");
                ;
            }
            catch (Exception er)
            {
                MessageBox.Show("用户名添加失败！请检查字符是否正确,是否为空！", "Err提示！");
            }
            return true;
        }

        //删除用户
        public Boolean delete_user()
        {
            try
            {
                if (a_sn > -1 && dataGridView1.RowCount > 0 && dataGridView1.RowCount != a_sn)
                {
                    _DataTable.Rows.RemoveAt(a_sn);
                    GridviewShowDataTable(_DataTable, dataGridView1);
                    MessageBox.Show("用户名删除成功！", "提示！");
                }
            }
            catch (Exception er)
            { MessageBox.Show("用户名删除失败！", "Err提示！"); return false; }
            return true;
        }

        //修改用户
        public Boolean update_user()
        {
            try
            {
                //判断不能为空
                if ((text_User.Text == string.Empty) || (text_admin.Text == string.Empty) || (text_passwordA.Text == string.Empty) || (text_passwordB.Text == string.Empty) || (text_password.Text == string.Empty))
                {
                    MessageBox.Show("有项目为空，请重新输入!", "系统提示");
                    return false;
                }

                //判断密码二次输入是否正确
                if (text_passwordB.Text.Trim() != text_password.Text.Trim())
                {
                    MessageBox.Show("新密码两次输入不匹配。请重新输入！", "Err提示！");
                    return false;
                }

                //判断旧密码是否正确
                DataRow[] drs = _DataTable.Select("用户='"+ text_User.Text+"'");
                string bufPass = drs[0]["密码"].ToString();

                string bufdtr = Sha1Sign(text_password.Text, Encoding.UTF8);
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 != comparer.Compare(bufPass, bufdtr))
                {
                    MessageBox.Show("旧密码不正确，请重新输入！", "Err提示！");
                    return false;
                }

                //开始写入
                if (a_sn>=0)
                {
                    _DataTable.Rows[a_sn][2] = bufdtr;
                }
                
                GridviewShowDataTable(_DataTable, dataGridView1);
                MessageBox.Show("用户名修改成功！", "提示！");
                
            }
            catch (Exception er)
            {
                MessageBox.Show("用户名修改失败！请检查字符是否正确,是否为空！", "Err提示！");
            }
            return true;
        }


        /*****************************************************************************************************/

        public int Serialize<T>(T source, string file_path)//序列化方法  
        {
            if (!typeof(T).IsSerializable)
            {
                //MessageBox.Show("类型必须是可序列化", "提示");
                return 1;
            }

            if (Object.ReferenceEquals(source, null))
            {
                //MessageBox.Show("实例不是相同的实例", "提示");
                return 2;
            }
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Create))//创建一个文件流，对文件进行写入FileMode.Create
                {
                    BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                    bf.Serialize(fs, source); //序列化到硬盘
                    fs.Close();//关闭文件流
                }
                return 0;
            }
            catch
            {
                return 3;
            }
        }
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open)) //FileStream FileMode.Open
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// DataTable表数据显示到DataGridview 必须要有列名并与DataTable对齐
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="dataGridView">DataGridView</param>
        /// <returns>true成功；false失败</returns>
        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                dataGridView.Rows.Clear();
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        dataGridView.Rows.Add();
                        for (int j = 0; j < (table.Columns.Count-1); j++)
                        {
                            dataGridView.Rows[i].Cells[j+1].Value = table.Rows[i].ItemArray[j].ToString();
                            //Application.DoEvents();//可以交出控制权但是慢
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        /// <summary>
        /// DataGridView导出为Datatable
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>Datatable</returns>
        public DataTable GetDataGridView(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].FormattedValue);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// SHA1加密
        /// </summary>
        /// <param name="content">待加密的字符串</param>
        /// <param name="encode">编码方式</param>
        /// <returns></returns>
        public string Sha1Sign(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();//创建SHA1对象
                byte[] bytes_in = encode.GetBytes(content);//将待加密字符串转为byte类型
                byte[] bytes_out = sha1.ComputeHash(bytes_in);//Hash运算
                sha1.Dispose();//释放当前实例使用的所有资源
                String result = BitConverter.ToString(bytes_out);//将运算结果转为string类型
                result = result.Replace("-", "").ToUpper();
                return result;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        //返回鼠标点击行的所有数据
        private string[] gridview_tobox(int Rows, int columns)
        {
            a_sn = Rows;
            string[] tabel_str = new string[dataGridView1.Columns.Count];
            try
            {
                if (Rows > -1)
                {
                    for (int j = 0; j < (dataGridView1.Columns.Count); j++)
                    {
                        tabel_str[j] = Convert.ToString(dataGridView1.Rows[Rows].Cells[j].Value);
                    }
                    return tabel_str;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }

        private void text_admin_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
